<template>
  <div class="max-w-4xl mx-auto">
    <!-- 返回按钮 -->
    <button
      @click="navigateToProblemSets"
      class="flex items-center text-blue-600 hover:text-blue-800 mb-6 transition-colors"
    >
      <ArrowLeft class="h-5 w-5 mr-2" />
      返回题目集
    </button>

    <!-- 题目标题和基本信息 -->
    <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
      <div class="flex items-start justify-between mb-4">
        <div class="flex-1">
          <div class="flex items-center gap-2 mb-3">
            <span
              v-if="problem.isRecommended"
              class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800"
            >
              <Star class="h-3 w-3 mr-1 fill-current" />
              推荐
            </span>
            <span
              :class="`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${getDifficultyColor(
                problem.difficulty
              )}`"
            >
              {{ problem.difficulty }}
            </span>
          </div>
          <h1 class="text-2xl font-bold text-gray-900 mb-2">{{ problem.title }}</h1>
          <p class="text-gray-600 mb-4">{{ problem.description }}</p>
        </div>
      </div>

      <div class="flex items-center justify-between text-sm text-gray-500 mb-4">
        <div class="flex items-center space-x-4">
          <div class="flex items-center">
            <component :is="getCategoryIcon(problem.category)" class="h-4 w-4" />
            <span class="ml-1">{{ problem.category }}</span>
          </div>
          <div class="flex items-center">
            <Clock class="h-4 w-4 mr-1" />
            <span>{{ problem.estimatedTime }}分钟</span>
          </div>
          <div class="flex items-center">
            <Users class="h-4 w-4 mr-1" />
            <span>{{ problem.attempts.toLocaleString() }}</span>
          </div>
        </div>
        <div class="text-green-600 font-medium">
          {{ problem.successRate }}% 成功率
        </div>
      </div>

      <div class="flex flex-wrap gap-2 mb-6">
        <span
          v-for="(tag, index) in problem.tags"
          :key="index"
          class="inline-flex items-center px-2 py-1 rounded-md text-xs bg-gray-100 text-gray-700"
        >
          {{ tag }}
        </span>
      </div>

      <button
        @click="handleStartSolving"
        class="w-full flex items-center justify-center px-6 py-3 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition-colors"
      >
        <Play class="h-5 w-5 mr-2" />
        开始解题
      </button>
    </div>

    <!-- 题目内容 -->
    <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
      <h2 class="text-xl font-bold mb-4">题目内容</h2>
      <div class="prose max-w-none">
        <p class="text-gray-700 mb-4">{{ problem.content }}</p>
        <div v-if="problem.mathFormula" class="bg-gray-50 rounded-lg p-4 my-4">
          <BlockMath :math="problem.mathFormula" />
        </div>
      </div>
    </div>

    <!-- 提示系统 -->
    <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
      <div class="flex items-center justify-between mb-4">
        <h2 class="text-xl font-bold">解题提示</h2>
        <button
          @click="showHints = !showHints"
          class="text-blue-600 hover:text-blue-800 text-sm font-medium"
        >
          {{ showHints ? '隐藏提示' : '显示提示' }}
        </button>
      </div>

      <div v-if="showHints" class="space-y-3">
        <div
          v-for="(hint, index) in problem.hints.slice(0, currentHint + 1)"
          :key="index"
          class="flex items-start p-3 bg-blue-50 rounded-lg"
        >
          <div class="flex-shrink-0 w-6 h-6 rounded-full bg-blue-100 flex items-center justify-center text-xs font-medium text-blue-600 mr-3 mt-0.5">
            {{ index + 1 }}
          </div>
          <p class="text-blue-800">{{ hint }}</p>
        </div>
        
        <button
          v-if="currentHint < problem.hints.length - 1"
          @click="showNextHint"
          class="text-blue-600 hover:text-blue-800 text-sm font-medium"
        >
          显示下一个提示
        </button>
      </div>
    </div>

    <!-- 解答步骤 -->
    <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
      <div class="flex items-center justify-between mb-4">
        <h2 class="text-xl font-bold">标准解答</h2>
        <button
          @click="showSolution = !showSolution"
          class="text-blue-600 hover:text-blue-800 text-sm font-medium"
        >
          {{ showSolution ? '隐藏解答' : '查看解答' }}
        </button>
      </div>

      <div v-if="showSolution" class="space-y-4">
        <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
          <div class="flex items-start">
            <AlertCircle class="h-5 w-5 text-yellow-600 mt-0.5 mr-2" />
            <p class="text-yellow-800 text-sm">
              建议先尝试自己解答，再查看标准解答进行对比学习。
            </p>
          </div>
        </div>

        <div>
          <h3 class="font-semibold mb-3">解题步骤：</h3>
          <ol class="space-y-2">
            <li
              v-for="(step, index) in problem.solution.steps"
              :key="index"
              class="flex items-start"
            >
              <span class="flex-shrink-0 w-6 h-6 rounded-full bg-green-100 flex items-center justify-center text-xs font-medium text-green-600 mr-3 mt-0.5">
                {{ index + 1 }}
              </span>
              <span class="text-gray-700">{{ step }}</span>
            </li>
          </ol>
        </div>

        <div class="bg-gray-50 rounded-lg p-4">
          <h3 class="font-semibold mb-2">解题思路：</h3>
          <p class="text-gray-700">{{ problem.solution.explanation }}</p>
        </div>
      </div>
    </div>

    <!-- 相关题目推荐 -->
    <div class="bg-white rounded-xl shadow-sm p-6">
      <h2 class="text-xl font-bold mb-4">相关几何题目推荐</h2>
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <button
          v-for="(relatedId, index) in problem.relatedProblems"
          :key="relatedId"
          @click="navigateToRelatedProblem(relatedId)"
          class="p-4 border border-gray-200 rounded-lg hover:border-blue-300 hover:bg-blue-50 transition-colors text-left"
        >
          <h3 class="font-medium text-gray-900 mb-1">
            相关几何题目 {{ index + 1 }}
          </h3>
          <p class="text-sm text-gray-600">
            {{ getCategory(relatedId) }} · {{ getDifficultyLevel(relatedId) }}
          </p>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {
  ArrowLeft,
  Clock,
  Users,
  Star,
  Target,
  BookOpen,
  TrendingUp,
  Award,
  Play,
  CheckCircle,
  AlertCircle,
} from 'lucide-vue-next';
// import { problemService } from '../services/apiService';

const route = useRoute();
const router = useRouter();

const problem = ref({
  id: '',
  title: '',
  description: '',
  content: '',
  difficulty: '',
  category: '',
  estimatedTime: 0,
  attempts: 0,
  successRate: 0,
  tags: [],
  isRecommended: false,
  score: 0,
  mathFormula: '',
  hints: [],
  solution: {
    steps: [],
    explanation: '',
  },
  relatedProblems: [],
});

const loading = ref(true);
const error = ref(null);
const showSolution = ref(false);
const showHints = ref(false);
const currentHint = ref(0);

onMounted(() => {
  if (route.params.id) {
    fetchProblemDetail(route.params.id);
  }
});

const fetchProblemDetail = async (problemId) => {
  try {
    loading.value = true;
    
    // Try to fetch from API first
    try {
      const apiData = await problemService.getProblemDetail(problemId);
      problem.value = apiData;
      error.value = null;
      return;
    } catch (apiError) {
      console.warn('API failed, using fallback data:', apiError);
    }

    // Fallback to mock data if API fails
    problem.value = {
      id: problemId,
      title: `几何题目 ${problemId}`,
      description: generateDescription(problemId),
      content: generateProblemContent(problemId),
      difficulty: getDifficultyLevel(problemId),
      category: getCategory(problemId),
      estimatedTime: Math.floor(Math.random() * 25) + 5,
      attempts: Math.floor(Math.random() * 2000) + 100,
      successRate: Math.floor(Math.random() * 40) + 60,
      tags: generateTags(problemId),
      isRecommended: Math.random() > 0.7,
      score: Math.floor(Math.random() * 30) + 70,
      mathFormula: generateMathFormula(problemId),
      hints: generateHints(problemId),
      solution: {
        steps: generateSolutionSteps(problemId),
        explanation: generateSolutionExplanation(problemId),
      },
      relatedProblems: generateRelatedProblems(problemId),
    };
    error.value = null;
  } catch (err) {
    console.error('Failed to fetch problem detail:', err);
    error.value = '获取题目详情失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

const generateDescription = (id) => {
  const descriptions = [
    '证明三角形全等，运用SAS、ASA、SSS定理',
    '计算圆的面积和周长，掌握圆的基本性质',
    '求解三角形的面积，运用海伦公式和正弦定理',
    '证明四边形的性质，分析平行四边形特征',
    '计算立体图形的体积，掌握棱锥和圆锥公式',
    '分析角的平分线性质，运用几何定理证明',
    '求解相似三角形的比例关系和对应边',
    '计算多边形的内角和与外角和',
    '证明圆的切线性质，运用切线定理',
    '分析空间几何中的平行与垂直关系',
  ];
  return descriptions[parseInt(id) % descriptions.length];
};

const generateProblemContent = (id) => {
  const contents = [
    '在三角形ABC中，已知AB = AC，∠BAC = 60°，求证：三角形ABC是等边三角形。',
    '已知圆O的半径为5cm，求圆的面积和周长。',
    '在三角形ABC中，已知a = 6，b = 8，c = 10，求三角形的面积。',
    '在平行四边形ABCD中，已知∠A = 60°，AB = 4，AD = 6，求平行四边形的面积。',
    '已知正四面体的棱长为a，求其体积和表面积。',
    '在三角形ABC中，AD是∠BAC的平分线，求证：BD/DC = AB/AC。',
    '已知三角形ABC与三角形DEF相似，相似比为2:3，若三角形ABC的面积为12，求三角形DEF的面积。',
    '求正六边形的内角和与外角和。',
    '已知圆O的半径为r，PA是圆的切线，切点为A，求证：PA²= PO² - r²。',
    '在正方体ABCD-A₁B₁C₁D₁中，求证：AC₁⊥平面A₁BD。',
  ];
  return contents[parseInt(id) % contents.length];
};

const generateMathFormula = (id) => {
  const formulas = [
    'AB = AC, \\angle BAC = 60°',
    'S = \\pi r^2, C = 2\\pi r',
    'S = \\sqrt{s(s-a)(s-b)(s-c)}',
    'S = ab\\sin C',
    'V = \\frac{\\sqrt{2}}{12}a^3',
    '\\frac{BD}{DC} = \\frac{AB}{AC}',
    '\\frac{S_{DEF}}{S_{ABC}} = \\left(\\frac{3}{2}\\right)^2',
    '\\text{内角和} = (n-2) \\times 180°',
    'PA^2 = PO^2 - r^2',
    'AC_1 \\perp \\text{平面} A_1BD',
  ];
  return formulas[parseInt(id) % formulas.length];
};

const generateHints = (id) => {
  const hintSets = [
    ['考虑等腰三角形的性质', '利用已知角度条件', '运用三角形内角和定理'],
    ['回忆圆的面积公式', '注意π的使用', '检查单位是否正确'],
    ['使用海伦公式', '先计算半周长s', '注意开方运算'],
    ['利用平行四边形面积公式', '注意角度的正弦值', '检查边长单位'],
    ['回忆正四面体的性质', '利用立体几何公式', '注意体积单位'],
  ];
  return hintSets[parseInt(id) % hintSets.length];
};

const generateSolutionSteps = (id) => {
  const stepSets = [
    [
      '根据已知条件AB = AC，确定三角形ABC是等腰三角形',
      '利用∠BAC = 60°和等腰三角形性质',
      '计算∠ABC = ∠ACB = (180° - 60°)/2 = 60°',
      '得出三个内角都是60°，因此是等边三角形',
    ],
    [
      '确定圆的半径r = 5cm',
      '应用圆的面积公式S = πr²',
      '应用圆的周长公式C = 2πr',
      '计算得出最终结果',
    ],
    [
      '确定三边长a = 6，b = 8，c = 10',
      '计算半周长s = (a + b + c)/2 = 12',
      '应用海伦公式S = √[s(s-a)(s-b)(s-c)]',
      '计算得出面积S = 24',
    ],
  ];
  return stepSets[parseInt(id) % stepSets.length];
};

const generateSolutionExplanation = (id) => {
  const explanations = [
    '通过等腰三角形的性质和角度条件，我们可以系统地证明三角形是等边三角形。关键是利用等腰三角形底角相等的性质。',
    '圆的面积和周长计算是几何学的基础。正确应用公式并注意π的精确值是解题的关键。',
    '海伦公式是计算三角形面积的重要方法，特别适用于已知三边长的情况。计算时要注意运算的准确性。',
  ];
  return explanations[parseInt(id) % explanations.length];
};

const generateRelatedProblems = (id) => {
  const baseId = parseInt(id);
  return [`problem-${baseId + 1}`, `problem-${baseId + 2}`, `problem-${baseId + 3}`];
};

const generateTags = (id) => {
  const allTags = [
    '三角形',
    '圆',
    '四边形',
    '相似',
    '全等',
    '面积',
    '体积',
    '证明',
    '计算',
    '定理',
  ];
  const numTags = Math.floor(Math.random() * 3) + 2;
  const startIndex = parseInt(id) % (allTags.length - numTags);
  return allTags.slice(startIndex, startIndex + numTags);
};

const getDifficultyLevel = (id) => {
  const levels = ['简单', '中等', '困难'];
  return levels[parseInt(id) % 3];
};

const getCategory = (id) => {
  const cats = ['平面几何', '立体几何', '解析几何', '向量几何'];
  return cats[parseInt(id) % cats.length];
};

const getDifficultyColor = (difficulty) => {
  switch (difficulty) {
    case '简单':
      return 'bg-green-100 text-green-800';
    case '中等':
      return 'bg-yellow-100 text-yellow-800';
    case '困难':
      return 'bg-red-100 text-red-800';
    default:
      return 'bg-gray-100 text-gray-800';
  }
};

const getCategoryIcon = (category) => {
  switch (category) {
    case '平面几何':
      return BookOpen;
    case '立体几何':
      return Target;
    case '解析几何':
      return TrendingUp;
    case '向量几何':
      return Award;
    default:
      return BookOpen;
  }
};

const handleStartSolving = () => {
  router.push({
    path: '/problems',
    state: { problemId: route.params.id, problemData: problem.value },
  });
};

const showNextHint = () => {
  if (currentHint.value < problem.value.hints.length - 1) {
    currentHint.value++;
  }
};

const navigateToProblemSets = () => {
  router.push('/problem-sets');
};

const navigateToRelatedProblem = (relatedId) => {
  router.push(`/problem-sets/${relatedId}`);
};
</script>
